import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.从请求中获取登陆密码
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username.equals("")||password.equals("")){
            resp.sendRedirect("login.html");
            return;
        }
        // 2.查询数据库,验证账号密码是否正确
        UserDao userDao = new UserDao();
        User user = null;
        try {
             user = userDao.selectByName(username);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 登录失败
        if (user == null || !user.getPassword().equals(password)){
            // resp.getWriter().write("账号或密码错误!登陆失败!");
            resp.sendRedirect("error.html");
            return;
        }
        // 登录成功
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blogList.html");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 针对登陆状态进行处理
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            resp.setStatus(403);
            return;
        }
        // 不写也行,默认就是200
        resp.setStatus(200);
    }
}
